import type {
	ActionFunctionArgs,
	LoaderFunctionArgs,
} from "@remix-run/cloudflare";
import { json, redirect } from "@remix-run/cloudflare";
import { useLoaderData } from "@remix-run/react";
import { useState, useEffect } from "react";
import { Input } from "app/components/ui/input";
import { Button } from "app/components/ui/button";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "app/components/ui/table";
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "app/components/ui/card";
import { Badge } from "app/components/ui/badge";
import { Search, Rss } from "lucide-react";
import { getSession, destroySession } from "~/sessions";
import { verify } from "~/db/auth";

export async function loader({ request, context }: LoaderFunctionArgs) {
	const session = await getSession(request.headers.get("Cookie"));

	if (session.has("token")) {
		const sessionId = session.get("token");
		const isVerified = await verify(
			context.cloudflare.env.D1DATA,
			sessionId as string,
		);
	}
	await destroySession(session);
	return redirect("/login");
}

export default function AdminHome() {
	const feeds = useLoaderData<typeof loader>();
	const [rssUrl, setRssUrl] = useState("");
	const [searchResults, setSearchResults] = useState([]);
	const [subscriptions, setSubscriptions] = useState([]);
	const [downloadStatus, setDownloadStatus] = useState({});

	// 模拟搜索 RSS
	const searchRSS = () => {
		// 这里应该是一个实际的 API 调用
		const mockResults = [
			{ id: 1, title: "Tech News", url: "https://technews.com/rss" },
			{ id: 2, title: "Science Daily", url: "https://sciencedaily.com/rss" },
			{ id: 3, title: "World News", url: "https://worldnews.com/rss" },
		];
		setSearchResults(mockResults);
	};

	// 添加到订阅列表
	const addToSubscriptions = (item) => {
		if (!subscriptions.find((sub) => sub.id === item.id)) {
			setSubscriptions([...subscriptions, item]);
		}
	};

	// 模拟定时任务下载
	useEffect(() => {
		const interval = setInterval(() => {
			const newStatus = { ...downloadStatus };
			subscriptions.forEach((sub) => {
				newStatus[sub.id] = Math.random() > 0.5 ? "Success" : "Pending";
			});
			setDownloadStatus(newStatus);
		}, 5000); // 每5秒更新一次状态

		return () => clearInterval(interval);
	}, [subscriptions]);
	return (
		<>
			<div className="container mx-auto p-4 space-y-6">
				<Card>
					<CardHeader>
						<CardTitle>RSS Subscription Manager</CardTitle>
					</CardHeader>
					<CardContent>
						<div className="flex space-x-2">
							<Input
								type="url"
								placeholder="Enter RSS URL"
								value={rssUrl}
								onChange={(e) => setRssUrl(e.target.value)}
							/>
							<Button onClick={searchRSS}>
								<Search className="mr-2 h-4 w-4" /> Search
							</Button>
						</div>
					</CardContent>
				</Card>

				{searchResults.length > 0 && (
					<Card>
						<CardHeader>
							<CardTitle>Search Results</CardTitle>
						</CardHeader>
						<CardContent>
							<Table>
								<TableHeader>
									<TableRow>
										<TableHead>Title</TableHead>
										<TableHead>URL</TableHead>
										<TableHead>Action</TableHead>
									</TableRow>
								</TableHeader>
								<TableBody>
									{searchResults.map((item) => (
										<TableRow key={item.id}>
											<TableCell>{item.title}</TableCell>
											<TableCell>{item.url}</TableCell>
											<TableCell>
												<Button onClick={() => addToSubscriptions(item)}>
													Add
												</Button>
											</TableCell>
										</TableRow>
									))}
								</TableBody>
							</Table>
						</CardContent>
					</Card>
				)}

				<Card>
					<CardHeader>
						<CardTitle>Your Subscriptions</CardTitle>
					</CardHeader>
					<CardContent>
						<Table>
							<TableHeader>
								<TableRow>
									<TableHead>Title</TableHead>
									<TableHead>URL</TableHead>
									<TableHead>Status</TableHead>
								</TableRow>
							</TableHeader>
							<TableBody>
								{subscriptions.map((item) => (
									<TableRow key={item.id}>
										<TableCell>{item.title}</TableCell>
										<TableCell>{item.url}</TableCell>
										<TableCell>
											<Badge
												variant={
													downloadStatus[item.id] === "Success"
														? "success"
														: "secondary"
												}
											>
												{downloadStatus[item.id] || "Pending"}
											</Badge>
										</TableCell>
									</TableRow>
								))}
							</TableBody>
						</Table>
					</CardContent>
				</Card>
			</div>
		</>
	);
}
